package cn.itcast.backend2;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RoleInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Role roleAnnotation = handlerMethod.getMethodAnnotation(Role.class);

        if (roleAnnotation == null) {
            return true;
        }

        int requiredRole = roleAnnotation.value();
        int userRole = getUserRoleFromRequest(request); // 假设这里获取用户的角色

        if (userRole >= requiredRole) {
            return true;
        }

        // 权限不足，返回403 Forbidden
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Insufficient privileges");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private int getUserRoleFromRequest(HttpServletRequest request) {
        // 从请求中获取用户角色，假设这里是从session或token中获取
        String token = request.getHeader("Authorization");
        if ("admin-token".equals(token)) {
            return Role.ADMIN;
        } else if ("user-token".equals(token)) {
            return Role.USER;
        }
        return Role.GUEST;
    }
}
